package org.spiderflow.core.expression.parsing.ast.literal;

import org.spiderflow.core.expression.ExpressionError;
import org.spiderflow.core.expression.ExpressionTemplate;
import org.spiderflow.core.expression.ExpressionTemplateContext;
import org.spiderflow.core.expression.parsing.Span;
import org.spiderflow.core.expression.parsing.ast.Expression;

import java.io.IOException;

/**
 * A character literal, enclosed in single quotes. Supports escape sequences \n, \r,\t, \' and \\.
 *
 * @author zsh
 */
public class CharacterLiteral extends Expression {
    private final Character value;

    public CharacterLiteral(Span literal) {
        super(literal);

        String text = literal.getText();
        if (text.length() > 3) {
            if (text.charAt(2) == 'n') {
                value = '\n';
            } else if (text.charAt(2) == 'r') {
                value = '\r';
            } else if (text.charAt(2) == 't') {
                value = '\t';
            } else if (text.charAt(2) == '\\') {
                value = '\\';
            } else if (text.charAt(2) == '\'') {
                value = '\'';
            } else {
                throw ExpressionError.error("Unknown escape sequence '" + literal.getText() + "'.", literal);
            }
        } else {
            this.value = literal.getText().charAt(1);
        }
    }

    public Character getValue() {
        return value;
    }

    @Override
    public Object evaluate(ExpressionTemplate template, ExpressionTemplateContext context) throws IOException {
        return value;
    }
}